package edu.fudan.cse.medlab.event.moresite;

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.FileReader;
import java.io.FileWriter;


public class SeedEvent {
	public void expandSeedEvent(String seedevent,HostManager hm)throws Exception{
		BufferedReader bin = new BufferedReader(new FileReader(seedevent));
		String s;
	//	String temp = "";
		String[] keywords;
		while( (s=bin.readLine()) != null){
			keywords = s.split("\\t| ");
			java.net.URL[] urls = Google.SearchByKeyword(keywords,30);
			for (int k = 0; k < urls.length; k++) {
				System.out.println(k+":   "+urls[k]);
				System.out.println(urls[k].getHost());
				hm.add(urls[k].getHost());
			}
		}
	}
	
//	public int getEventNum(String[] sites) throws Exception{
//		int k = 0;
//		for (int i = 0; i < sites.length; i++) {
//			k += DB.getEventNumForSite(sites[i]);
//		}
//		return k;
//	}

	public String[] readSites(String hm,String blacklist, int sitenum) throws Exception{
		BufferedReader bin=new BufferedReader(new FileReader(blacklist));
		String s;
		String blacksite = "";
		while((s = bin.readLine())!=null){
			blacksite +=s;
		}
		
		bin=new BufferedReader(new FileReader(hm));
	
		int k = 0;
		String[] sites = new String[sitenum];
		while((s = bin.readLine())!=null){
			if(k >= sitenum)
				break;
			if(blacksite.contains(s.substring(0,s.indexOf(":"))))
				continue;
			sites[k++] = s.substring(0,s.indexOf(":"));
		}
		bin.close();
		return sites;
	}
	
	public void writeSeedSites(String[] seedsites,String seedfile) throws Exception{
		BufferedWriter bout=new BufferedWriter(new FileWriter(seedfile));
		for (int i = 0; i < seedsites.length; i++) {
			bout.write(seedsites[i]+ "\r\n");	
			bout.flush();
		}
		bout.close();	
	}
	
	
	public static String[] getSeedSites(String seedfile) {
		String seedevent = "seedevent.txt";
		HostManager hm = new HostManager("hostmanager.txt");
		SeedEvent ts = new SeedEvent();
	//	Settings setting = new Settings();
		try{
			ts.expandSeedEvent(seedevent, hm);
			hm.sort();
			hm.writeToFile();
			String[] seedsites = ts.readSites("hostmanager.txt","blacklist.txt", 5);	
			ts.writeSeedSites(seedsites, seedfile);
			return seedsites;
		}
		catch(Exception e){
			e.printStackTrace();
			return null;
		}
	}
}
